#define _CRT_SECURE_NO_WARNINGS 1

#include <iostream>
#include <string>
#include <WinSock2.h>

#pragma comment(lib, "ws2_32.lib")
#pragma warning(disable:4996)

uint16_t serverport = 8888;
std::string serverip = "47.120.34.136";

int main()
{
	WSADATA WSAData;

	if (WSAStartup(MAKEWORD(2, 2), &WSAData) != 0)//检查引入的库和期望用的版本是否一致
	{
		std::cerr << "init error" << std::endl;
		return -1;
	}

    // 创建socket接口，打开网络文件
    SOCKET sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0)
    {
        std::cerr << "create socket error" << std::endl;
        exit(-2);
    }

    // 明确server是谁
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(serverip.c_str());
    server.sin_port = htons(serverport);

    while (true)
    {
        // 用户输入
        std::string message;
        std::cout << "Please Enter Your Message# ";//2
        // std::cin >> message;
        std::getline(std::cin, message);

        // 发送
        // 在我们首次系统调用发送数据时，OS会在底层随机选择cilentport+自己的IP进行bind，并构建发送的数据报文
        sendto(sock, message.c_str(), message.size(), 0, (struct sockaddr*)&server, sizeof(server));

        //接收
        char buffer[2048];
        struct sockaddr_in temp;
        int len = sizeof(temp);
        int n = recvfrom(sock, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&temp, &len);
        if (n > 0)
        {
            buffer[n] = '\0';
            std::cout << buffer << std::endl;//1
        }
    }
    closesocket(sock);
	WSACleanup();//清理所使用的的资源
	return 0;
}